<?php
class Acl extends Zend_Controller_Plugin_Abstract
{
	public function routeShutdown(Zend_Controller_Request_Abstract $request){

		if (Zend_Auth::getInstance()->hasIdentity()){
			$role = App_Model_Auth::isAdmin();
			if($role || Zend_Auth::getInstance()->getStorage()->read()->kod_roli == 'ADMIN')
				$role = 'admin';
			else
				$role = 'member';
		} else{
			$role = 'guest'; 
		}

		$acl = new Zend_Acl();
		
		$acl->addRole(new Zend_Acl_Role('guest'));
		$acl->addRole(new Zend_Acl_Role('member'), 'guest');
		$acl->addRole(new Zend_Acl_Role('admin'), 'member');

		$acl->addResource(new Zend_Acl_Resource('app:index'));
		$acl->addResource(new Zend_Acl_Resource('app:error'));
		$acl->addResource(new Zend_Acl_Resource('app:edit'));
 
		$acl->addResource(new Zend_Acl_Resource('admin:index'));
                $acl->addResource(new Zend_Acl_Resource('admin:users'));


		if(!$acl->has($request->getModuleName() . ':' . 
					  $request->getControllerName(),
					  $request->getActionName())){
			
					  	
			//throw new Zend_Exception("Podane źródło nie istnieje");	
			$request->setControllerName('index');
            $request->setActionName('index');
            $request->setModuleName('app');

            $response = $this->getResponse();
            $response->setRedirect('/');		  	
		}
		
		$acl->deny(array('guest','member', 'admin'));
		
		$acl->allow('guest', 'app:index', array('index'));//logowanie
		$acl->deny('member', 'admin:index');
		$acl->allow('member', array('app:index'), null);
  		$acl->allow('admin', array('admin:index','admin:users','app:edit'),null);

		
		if (!$acl->isAllowed( $role,
			  $request->getModuleName() . ':' . 
			  $request->getControllerName(),
			  $request->getActionName())
		) {

            $request->setControllerName('index');
            $request->setActionName('index');
            $request->setModuleName('app');

            $response = $this->getResponse();
            $response->setRedirect('/');
      }
	}
}
